package com.zhiyume.oss;

import com.zhiyume.service.util.DateUtil;
import com.zhiyume.util.OSSClientUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FroalaEditor测试
 */
@Controller
@RequestMapping("/oss")
public class OssUpload {

    @GetMapping(value="/ossImgUpload")
    public String ossUpload(){
        return "ossImgUpload";
    }

    /**
     * 上传至阿里云OSS
     * @param file
     * @param request
     * @param response
     * @throws FileNotFoundException
     */
    @PostMapping(value="/ossImgUpload")
    @ResponseBody
    public static Map ossUpload(@RequestParam(defaultValue="") String filedir,@RequestParam(value="file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {

        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String uploadFlag = "1"; // 0-上传成功 1-上传失败
        String uploadMsg = "上传成功"; // 上传返回提示

        List picInfo = new ArrayList();

        String uploadUrl = "";

        if (!file.isEmpty()) {
            try {
                BufferedImage image = ImageIO.read(file.getInputStream());
                fileName = DateUtil.date2String(new Date(), DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS) + "_" + fileName;

//                OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
//                String uploadStr = AliyunOSSClientUtil.uploadObject2OSS(ossClient,nFile,OSSClientConstants.BUCKET_NAME,"drama/");
//                String imgUrl = AliyunOSSClientUtil.getUrl(ossClient,OSSClientConstants.BUCKET_NAME,"");

                OSSClientUtil ossClientUtil = new OSSClientUtil(filedir);
                String md5Str = ossClientUtil.uploadImg2Oss(file);
                String imgUrl = ossClientUtil.getUrl("");

                picInfo.add(imgUrl);

                uploadUrl = imgUrl;

                System.out.println(">>>>>>>>>>上传文件至阿里云返回串<<<<<<<<<"+md5Str);

                System.out.println("------图片上传至阿里云的访问地址为---------" + imgUrl);
                /*
                示例：如您在Region为华北2，Bucketname为zhiyume-img，Object为drama/aaa.png，那么您的外网访问地址为：
                zhiyume-img.oss-cn-beijing.aliyuncs.com/drama/aaa.png
                您还可以直接将Object的URL链接放入HTML中使用，如下所示：
                <img src="https://zhiyume-img.oss-cn-beijing.aliyuncs.com/drama/aaa.png" />
                 */

                // 返回页面
                /*
                JSON结构如下:
                {"link":"http://i.froala.com/download/3d25b2b84a2d1045ce364111253c37fc4ca86f08.jpg?1508204919"}
                 */
                uploadFlag = "0";
                System.out.println("---------图片宽度-----"+image.getWidth()+"-------图片高度----"+image.getHeight());

            } catch (FileNotFoundException e) {
                uploadMsg = "上传失败,文件未找到";
                e.printStackTrace();
                //return "上传失败," + e.getMessage();
            } catch (IOException e) {
                uploadMsg = "上传失败,文件读取出错";
                e.printStackTrace();
                //return "上传失败," + e.getMessage();
            } catch (Exception e) {
                uploadMsg = "上传失败";
                e.printStackTrace();
            }

        } else {
            //return "上传失败，因为文件是空的.";
            uploadFlag = "1";
            uploadMsg = "上传失败,图片不能为空";
        }

        Map<String,Object> data = new HashMap<String, Object>();
//        data.put("errno",uploadFlag);
//        data.put("data",picInfo);
        data.put("link",uploadUrl);

        return data;
    }

    /**
     * 图片删除
     * @param imgName
     */
    @RequestMapping("delPic")
    @ResponseBody
    public static Map delPic(@RequestParam String imgName){
        String result = "success";
        try {
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.deleteFile(imgName);
        }catch (Exception e){
            result = "fail";
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("result",result);
        return map;
    }

    /**
     * 删除指定目录下的指定图片
     * @param filedir
     * @param imgName
     * @return
     */
    @RequestMapping("delPicByDir")
    @ResponseBody
    public static Map delPic(@RequestParam String filedir,
                             @RequestParam String imgName){
        String result = "success";
        try {
            OSSClientUtil ossClientUtil = new OSSClientUtil(filedir);
            ossClientUtil.deleteFile(filedir,imgName);
        }catch (Exception e){
            result = "fail";
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("result",result);
        return map;
    }

    /**
     * 根据图片名字和阿里云裁剪样式进行图片处理
     * @return
     */
    public static String getImgStyleUrl(String style,String imgName){
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        String url = ossClientUtil.getImgSytleUrl(style,imgName);
        return url;
    }


    public static void main(String[] args) throws FileNotFoundException {
//        URL url = ResourceUtils.getURL("classpath:static/uploadImg/");
//        System.out.println(url.getPath());
//        System.out.println("123");
        OssUpload ossUpload = new OssUpload();
        String img = "data/20171017133709_psb.jpg";
        String style = "style/drama_width_height_rule";
        System.out.println("-----------阿里云图片处理后的地址为-----------"+ossUpload.getImgStyleUrl(style,img));
    }
}